//引入expressmok
var express = require('express');
//创建APP
var app = express();
//创建server
var server = require('http').createServer(app);
//引入body-parser用来接收post请求的数据
var bodyParser = require('body-parser');
//引入MD5加密
var md5 = require('./md5');
//引入用户数据源
var users = require('./datasource/user');
//引入multer模块（文件上传）
var multer = require('multer');
//引入文件模块FS
var fs = require('fs')

//photo：就是页面传过来的那个文件的namne，1代表最多能传一个
app.use(multer({ dest: 'tmp' }).array('photo', 1))
//引入path
var path = require('path');
//解析post
app.use(bodyParser.urlencoded({
    extended: true
}));
//托管静态文件
app.use(express.static(__dirname + '/assets'));
//网站的入口
app.get('/', (req, res) => {
    res.sendFile(__dirname + '/assets/pages/index.html')
});
//登录界面的入口
app.get('/login.html', (req, res) => {
    res.sendFile(__dirname + '/assets/pages/login.html')
});

//登录
app.post('/login.do', (req, res) => {
    let username = req.body.username;
    let password = md5(req.body.password);
    if (!username || !password) {
        res.send('fail');
        return;
    }
    for (u of users) {
        if (u.username === username && u.password === password && u.state == 1) {
            res.send('success');
            return
        }
    }
    res.send('fail');
});
//查询用户列表
app.get('/users.do', (req, res) => {
    res.send(users)
})



//重置用户密码
app.post('/resetPass.do', (req, res) => {
    let id = req.body.id;
    let new_pass = req.body.password;
    for (u of users) {
        if (u.id == id) {
            u.password = md5(new_pass);
            res.send('success');
            return
        }
    }
    red.send('fail');
})

//修改用户状态（1是正常，0是冻结）
app.post('/change_state.do', (req, res) => {
    let id = req.body.id;
    let state = req.body.state;
    for (u of users) {
        if (u.id == id) {
            u.state = state;
            res.send('success');
            return;
        }
    }
    res.send('fail');
})

//添加新用户
app.post('/addUser.do', (req, res) => {
    let username = req.body.username;
    let password = md5(req.body.password);
    let phone = req.body.phone;
    let id = users[users.length - 1].id + 1;
    let state = 1;
    if (username && password && phone) {
        users.push({
            username, password, phone, id, state
        });
        res.send('success');
    } else {
        res.send('fail');
    }

})
//添加角色
var roles = require('./datasource/role');
app.get('/role.do', (req, res) => {
    res.send(roles)
})
app.post('/addRole.do', function (req, res) {
    let role = req.body.username;
    roles.push(role);
    res.send('success');
})
//添加员工
//引入员工数据源
var empls = require('./datasource/employee');
//引入rimraf
var rimraf = require('rimraf');
//查询员工列表
app.get('/employee.do', (req, res) => {
    res.send(empls)
})
app.post('/addEmployee.do', (req, res) => {
    var file = req.files[0];
    //获取原始文件的名字
    var url = __dirname + '/assets/img/' + file.originalname;
    //读取数据
    var data = fs.readFileSync(file.path);

    fs.writeFile(url, data, function (err) {
        if (err) {

            console.error(err);
        }

        rimraf(__dirname + '/tmp/*', function (err) {
            console.log(err);
        })
    })
    let id = empls[empls.length - 1].id + 1;
    let em = {
        id,
        name: req.body.name,
        age: req.body.age,
        sex: req.body.sex,
        phone: req.body.phone,
        idCard: req.body.idCard,
        role: req.body.role,
        photo: file.originalname,
        state: req.body.state
    }
    console.log(em);
    empls.push(em);
    res.send('success');


})
//删除员工
app.post('/del.do', function (req, res) {
    let id = req.body.id;
    for (let i = 0; i < empls.length; i++) {
        let value = empls[i];
        if (value.id == id) {
            //先删除图片
            let url = __dirname + '/assets/img/' + value.photo;
            try {
            fs.unlinkSync(url);
            }catch(error){
            fs.appendFile(__dirname+'/log/error.text',error.message,(err)=>{
                if(err)throw err;
            });
            
            res.send('success');
            return
            }
        //再从这个数组删除这个人的信息
        empls.splice(i,1);
        res.send('success');
        return;
        }
    }
    res.send('fail')
})
//修改员工
// app.post('/del_xiugai.do', (req, res) => {
//     let id = req.body.id;
//     let name = req.body.name;
//     let phone = req.body.phone;
//     let idCard = req.body.idCard;
//     let age = req.body.age;
//     let role = req.body.role;
//     let sex = req.body.sex;
//     for (u of empls) {
//         if (u.id == id) {
//             u.name = name;
//             u.phone = phone;
//             u.idCard = idCard;
//             u.age = age;
//             u.role = role;
//             u.sex = sex;
//             res.send('success');
//             return
//         }
//     }
//     red.send('fail');
// })
//修改员工（根据员工ID查找这个员工的详细信息）
app.get('/queryEmployeebyld.do',(req,res)=>{
    let id =req.query.id;
    //filter:数组的过滤方法，根据函数里面的判断来返回一个新数组
    let newArr=empls.filter(value=>{
        return value.id ==id;
    })
    console.log(newArr);
    res.send(newArr[0]);
})


server.listen(8000);
console.log('==Hotel Manage Startup Success in 8000==')
